<?php
declare (strict_types = 1);

namespace app\service\basic\auth;

use InvalidArgumentException;

trait CreatesUserProviders
{
    /**
     * Create the user provider implementation for the driver.
     *
     * @param null $provider
     * @return ModelUserProvider
     */
    public function createUserProvider($provider = null)
    {
        if (is_null($config = $this->getProviderConfiguration($provider))) {
            throw new InvalidArgumentException(
                "Authentication user provider is not defined."
            );
        }

        $driver = $config['driver'] ?? null;

        switch ($driver) {
            case 'model':
                return $this->createEloquentProvider($config);
            default:
                throw new InvalidArgumentException(
                    "Authentication user provider [{$driver}] is not defined."
                );
        }
    }

    /**
     * Get the user provider configuration.
     *
     * @param $provider
     * @return mixed|void
     */
    protected function getProviderConfiguration($provider)
    {
        if ($provider = $provider ?: $this->getDefaultUserProvider()) {
            return $this->app->config->get('auth.providers.'.$provider);
        }
    }


    /**
     * Create an instance of the model user provider.
     *
     * @param $config
     * @return ModelUserProvider
     */
    protected function createEloquentProvider($config)
    {
        return new ModelUserProvider($config['model']);
    }

    /**
     * Get the default user provider name.
     *
     * @return string
     */
    public function getDefaultUserProvider()
    {
        return $this->app->config->get('auth.defaults.provider');
    }
}
